package com.efounder.email.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.ospmobilelib.R;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.email.adapter.MyGridAdapter;
import com.efounder.email.contacts.SortModel;
import com.efounder.email.dao.ContactsDAO;
import com.efounder.email.model.AttachFile;
import com.efounder.email.model.Email;
import com.efounder.email.tags.TagGroup;
import com.efounder.email.util.AbStrUtil;
import com.efounder.email.util.AttaachDialog;
import com.efounder.email.util.FileSizeUtil;
import com.efounder.email.util.FileUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.StorageUtil;

/**
 * 写邮件
 * 
 * @author yqs
 * 
 */
public class EmailWriteAct extends Activity implements OnClickListener,
		OnFocusChangeListener, OnItemClickListener {
	final static String TAG = "EmailWriteAct";
	private StorageUtil storageUtil;
	String acType = "new";// 邮件类型
							// 新邮件是new，回复是reply，转发是forward，保存是save，回复的邮件保存是forwardsave
	final static int RECEIVETO = 1;// 表示收件
	final static int COPYTO = 2;// 表示抄送
	final static int SECTETTO = 3;// 表示密送
	// 取消和发送按钮
	// XXX 旧的 取消发送按钮
	// private Button cannelButton, sendbButton;
	// 新增收件人，新增抄送，，新增密送，附件
	private ImageView addPeopleImageView, copyToImageView, secretToImageView,
			addAttachmentImageView;
	private TextView titleTextView;// 标题的title

	private TagGroup recevierEText;// 收件人
	private TagGroup copyToEText;// 抄送
	private TagGroup secretToEText;// 密送
	private EditText emailThemeEText;// 邮件主题
	private EditText emailContentEText;// 邮件内容
	private TextView addresserTextView, addresserTextView1;// 发件人
	private TextView hideFajianrenName, hideFajianrenEmail,
			hideShoujianrenName, hideShoujianrenEmail, hideTime, hideTheme;
	private ImageView[] imageViews;// add图标数组
	private ImageView addFileView;// 添加文件附件
	private ImageView addImageView;// 添加图片附件
	private WebView webView;
	private GridView gridView;
	private MyGridAdapter gridAdapter;
	private EditText[] editTexts;
	private String path;// 文件的绝对路径
	List<String> tagArray;// 联系人标签tag list
	String[] tempArr;// 临时联系人标签tag list
	// 隐藏的抄送密送,回复邮件,隐藏的增加附件页面
	private LinearLayout invisibleLayout, textLinearLayout,
			shoujianrenInfoLayout, hideaddattachmentLayout;

	/** 附件list */
	ArrayList<AttachFile> files;
	/** 收件人list */
	ArrayList<SortModel> mSJRContacts;
	/** 抄送人list */
	ArrayList<SortModel> mCOPYContacts;
	/** 密送人人list */
	ArrayList<SortModel> mSECRETContacts;
	/** 数据库中所有的联系人 */
	ArrayList<SortModel> mAllContacts;
	Email emailData;
	String emailType;// 邮件类型 判断是 用总部邮箱还是普光邮箱 发送邮件

	String shoujianNames = "";
	String copytoNames = "";
	String secretToNames = "";
	String secretToAddress = "";
	String shoujianrenAddress = "";
	String copytoAddress = "";
	String fajianrenName = "";
	String fajianrenAddress = "";
	String emailTheme = "";
	String attachfiles = "";
	String content = "";
	String emailId = "";

	String[] filenameArray;
	int[] filesizeArray;
	Object[] byteArray;

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.writeemail);

		storageUtil = new StorageUtil(getApplicationContext(), "storage");
		// 类型为 DPEMAIL 或者 EMAIL
		emailType = (String) getIntent().getSerializableExtra("emailtype");
		initView();

		files = new ArrayList<AttachFile>();
		mSJRContacts = new ArrayList<SortModel>();
		mCOPYContacts = new ArrayList<SortModel>();
		mSECRETContacts = new ArrayList<SortModel>();
		if ("DPEMAIL".equals(emailType)) {
			//总部邮箱没有发送附件功能添加附件
			addAttachmentImageView.setVisibility(View.GONE);
		}

		// 如果intent中含有数据，说明是转发或者回复
		if (getIntent().hasExtra("copyto")) {
			titleTextView.setText("转发邮件");
			acType = "forward";	
			setHideShow(1);
		}
		if (getIntent().hasExtra("reply")) {
			titleTextView.setText("回复邮件");
			acType = "reply";
			if ("EMAIL".equals(emailType)) {
				acType = "new";
			}
			setHideShow(2);
		}

	}

	/**
	 * 初始化view
	 */
	private void initView() {

		RelativeLayout include = (RelativeLayout) findViewById(R.id.include);
		include.setBackgroundResource(R.color.red_ios);
		LinearLayout leftbacklayout = (LinearLayout) findViewById(R.id.leftbacklayout);
		leftbacklayout.setVisibility(View.VISIBLE);
		titleTextView = (TextView) findViewById(R.id.fragmenttitle);// 标题
		titleTextView.setTextColor(Color.WHITE);
		if ("DPEMAIL".equals(emailType)) {
		titleTextView.setText("写邮件(总部)");
		}else {
			titleTextView.setText("写邮件(普光)");	
		}
		// 左上方返回按钮
		leftbacklayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		// 右上角发送按钮
		TextView sendTextView = (TextView) findViewById(R.id.meeting_date);
		sendTextView.setVisibility(View.VISIBLE);
		sendTextView.setTextSize(16);
		sendTextView.setText("发送");
		sendTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendEmail();// 发送邮件

			}
		});

		// cannelButton = (Button) findViewById(R.id.write_email_cannel);// 取消按钮
		// sendbButton = (Button) findViewById(R.id.write_email_send);// 发送按钮
		// cannelButton.setOnClickListener(this);
		// sendbButton.setOnClickListener(this);
		webView = (WebView) findViewById(R.id.shoujian_webview);// 写邮件页面的webview

		// titleTextView = (TextView) findViewById(R.id.write_title);//
		// 上方title标题

		gridView = (GridView) findViewById(R.id.grid);
		gridView.setOnItemClickListener(this);
		addFileView = (ImageView) findViewById(R.id.add_fileres);// 弹出框新增文件
		addImageView = (ImageView) findViewById(R.id.add_imageres);// 弹出框新增图片附件
		addFileView.setOnClickListener(this);
		addImageView.setOnClickListener(this);

		addPeopleImageView = (ImageView) findViewById(R.id.write_addpeople);// 新增收件人图标
		copyToImageView = (ImageView) findViewById(R.id.copyto_add);// 新增抄送人图标
		secretToImageView = (ImageView) findViewById(R.id.secretsend_add);// 新增密送人图标
		addAttachmentImageView = (ImageView) findViewById(R.id.write_addattachment);// 右下方新增附件按钮
		addAttachmentImageView.setOnClickListener(this);
		imageViews = new ImageView[] { addPeopleImageView, copyToImageView,
				secretToImageView };
		for (ImageView image : imageViews) {
			image.setOnClickListener(this);
		}

		recevierEText = (TagGroup) findViewById(R.id.email_receiver);// 收件人编辑框
		recevierEText.setOnClickListener(this);
		recevierEText.setOnFocusChangeListener(this);
		recevierEText.setOnTagClickListener(mSJRTagCkListener);

		copyToEText = (TagGroup) findViewById(R.id.copyto);// 抄送人编辑框
		secretToEText = (TagGroup) findViewById(R.id.secretsend);
		copyToEText.setOnTagClickListener(mCopyTagCkListener);
		secretToEText.setOnTagClickListener(mSecretClickListener);
		emailThemeEText = (EditText) findViewById(R.id.write_emal_theme);// 邮件主题编辑框
		emailContentEText = (EditText) findViewById(R.id.write_email_content);// 邮件内容编辑框

		copyToEText.setOnClickListener(this);
		secretToEText.setOnClickListener(this);
		editTexts = new EditText[] { emailThemeEText, emailContentEText };
		for (EditText editText : editTexts) {
			editText.setOnFocusChangeListener(this);
			editText.setOnClickListener(this);
		}

		hideFajianrenEmail = (TextView) findViewById(R.id.fajianren_address);
		hideFajianrenEmail.setVisibility(View.INVISIBLE);

		hideFajianrenName = (TextView) findViewById(R.id.fajianren_name);
		hideShoujianrenEmail = (TextView) findViewById(R.id.shoujianren_address);
		hideShoujianrenEmail.setVisibility(View.INVISIBLE);
		hideShoujianrenName = (TextView) findViewById(R.id.shoujianren_name);
		hideTheme = (TextView) findViewById(R.id.shoujian_theme);
		hideTime = (TextView) findViewById(R.id.fajian_time);
		// 发件人
		addresserTextView = (TextView) findViewById(R.id.write_emal_addresser);
		addresserTextView1 = (TextView) findViewById(R.id.write_emal_addresser1);
		addresserTextView.setText(storageUtil.getString("loginUserName"));
		addresserTextView1.setText(storageUtil.getString("loginUserName"));

		invisibleLayout = (LinearLayout) findViewById(R.id.write_email_visible);
		textLinearLayout = (LinearLayout) findViewById(R.id.write_email_textview);
		shoujianrenInfoLayout = (LinearLayout) findViewById(R.id.shoujian_info);
		hideaddattachmentLayout = (LinearLayout) findViewById(R.id.hide_addfile);// 隐藏的选择附件的layout

		textLinearLayout.setOnClickListener(this);
		textLinearLayout.setOnFocusChangeListener(this);

	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		// // 取消按钮
		// case R.id.write_email_cannel:
		// this.finish();
		// break;
		// // 发送按钮
		// case R.id.write_email_send:
		// sendEmail();
		//
		// break;
		if (v.getId() == R.id.email_receiver) {// 新增收件人那一行
			hideAddImage(addPeopleImageView);
			if (copyToEText.getTags().length <= 0
					|| copyToEText.getTags() == null) {
				invisibleLayout.setVisibility(View.GONE);
				textLinearLayout.setVisibility(View.VISIBLE);
			}
		}else if (v.getId() == R.id.copyto) {// 新增抄送人那一行
			hideAddImage(copyToImageView);
		}else if (v.getId() == R.id.secretsend) {// 新增密送人那一行
			hideAddImage(secretToImageView);
		}else if (v.getId() == R.id.write_addpeople) {// 新增收件人按钮
			getInputContact(RECEIVETO);
			// Intent intent = new Intent(this, EmailLinkManAct.class);
			// intent.putExtra("flag", "add_addresser");
			// startActivityForResult(intent, 0);
			Toast.makeText(EmailWriteAct.this, "正在开发中...", Toast.LENGTH_SHORT)
					.show();
		}else if (v.getId() == R.id.copyto_add) {// 新增抄送人按钮
			getInputContact(COPYTO);
			Toast.makeText(EmailWriteAct.this, "正在开发中...", Toast.LENGTH_SHORT)
					.show();
			// Intent intent1 = new Intent(this, EmailLinkManAct.class);
			// intent1.putExtra("flag", "add_copy");
			// startActivityForResult(intent1, 0);
		}else if (v.getId() == R.id.secretsend_add) {// 新增秘送人按钮
			getInputContact(SECTETTO);
			Toast.makeText(EmailWriteAct.this, "正在开发中...", Toast.LENGTH_SHORT)
					.show();
			// Intent intent2 = new Intent(this, EmailLinkManAct.class);
			// intent2.putExtra("flag", "add_secret");
			// startActivityForResult(intent2, 0);
		}else if (v.getId() == R.id.write_email_textview) {// 点击抄送密送那一行
			textLinearLayout.setVisibility(View.GONE);
			invisibleLayout.setVisibility(View.VISIBLE);
			hideAddImage(null);
		}else if (v.getId() == R.id.write_addattachment) {// 右下角增加附件的按钮
			// 隐藏输入法
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			// boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开

			// im.hideSoftInputFromWindow(emailContentEText.getWindowToken(),
			// InputMethodManager.HIDE_NOT_ALWAYS);
			imm.hideSoftInputFromWindow(emailContentEText.getWindowToken(), 0); // 强制隐藏键盘

			if (hideaddattachmentLayout.getVisibility() == View.VISIBLE) {
				hideaddattachmentLayout.setVisibility(View.GONE);
			} else {
				hideaddattachmentLayout.setVisibility(View.VISIBLE);
			}
		}else if (v.getId() == R.id.add_fileres) {// 下方弹出框新增
			textLinearLayout.setVisibility(View.VISIBLE);
			invisibleLayout.setVisibility(View.GONE);
			// Toast.makeText(this, "新增文件", Toast.LENGTH_SHORT).show();
			// hideAddImage(null);
			// 选择附件
			showFileChooser();
		}else if (v.getId() == R.id.add_imageres) {// 下方弹出框新增图片
			textLinearLayout.setVisibility(View.VISIBLE);
			invisibleLayout.setVisibility(View.GONE);
			// Toast.makeText(this, "新增图片", Toast.LENGTH_SHORT).show();
			/*
			 * Intent i = new Intent( Intent.ACTION_PICK,
			 * android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			 * startActivityForResult(i, 2);
			 */
			startActivity(new Intent(this, PhotoWallActivity.class));
		}
		int id = v.getId();
		if (id == R.id.write_email_content || id == R.id.write_emal_theme
				|| id == R.id.email_receiver) {
			if (copyToEText.getTags().length <= 0
					|| copyToEText.getTags() == null) {
				invisibleLayout.setVisibility(View.GONE);
				textLinearLayout.setVisibility(View.VISIBLE);
			}
			hideaddattachmentLayout.setVisibility(View.GONE);
		}

	}

	/**
	 * 发送邮件
	 */
	private void sendEmail() {
		mAllContacts = new ContactsDAO(this).queryContacts();

		String[] receviers = recevierEText.getTags();
		String[] copyers = copyToEText.getTags();
		String[] secreters = secretToEText.getTags();

		// 收件人名字
		shoujianNames = AbStrUtil.getEmailContactsName(receviers, mAllContacts);
		// 收件人邮箱
		shoujianrenAddress = AbStrUtil.getEmailContactsAddress(receviers,
				mAllContacts);
		// 抄送人名字
		copytoNames = AbStrUtil.getEmailContactsName(copyers, mAllContacts);
		// 抄送人邮箱
		copytoAddress = AbStrUtil
				.getEmailContactsAddress(copyers, mAllContacts);
		// 密送人名字
		secretToNames = AbStrUtil.getEmailContactsName(secreters, mAllContacts);
		// 密送人邮箱
		secretToAddress = AbStrUtil.getEmailContactsAddress(secreters,
				mAllContacts);
		// 附件 名称
		// 如果是普光的附件，回复或者转发时要将附件重新发送
		if (files != null && files.size() > 0) {
		//	if (emailData != null) {
				if ("EMAIL".equals(emailType)) {
					filenameArray = new String[files.size()];
					filesizeArray = new int[files.size()];
					byteArray = new Object[files.size()];
					for (int i = 0; i < files.size(); i++) {
						filenameArray[i] = files.get(i).getAttachName();

						filesizeArray[i] = Integer.parseInt(files.get(i)
								.getAttachSize());

						try {
							byteArray[i] = FileUtil.toByteArray(files.get(i)
									.getAttachPath());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				else {
					for (int i = 0; i < files.size(); i++) {
						attachfiles = attachfiles + files.get(i).getAttachName()
								+ ",";
						attachfiles = attachfiles.substring(0,
								attachfiles.length() - 1);
					}
				}
		}
		// }
		// }

		// filenameArray = attachfiles.split(",");

		// 邮件内容
		if (emailType.equals("EMAIL")) {
			if (emailData != null) {
				content = "<p\r\n>" + emailContentEText.getText().toString()
						+ "<p\r\n>" + emailData.getContent();
			} else {
				content = emailContentEText.getText().toString();
			}

		} else if (emailType.equals("DPEMAIL")) {
			content = emailContentEText.getText().toString();
		}
		emailTheme = emailThemeEText.getText().toString();
		System.out.println("邮件内容:" + content);
		System.out.println("邮件主题:" + emailTheme);
		System.out.println("收件人名字:" + shoujianNames);
		System.out.println("收件人邮箱:" + shoujianrenAddress);
		System.out.println("附件名称:" + attachfiles);
		System.out.println("抄送人邮箱:" + copytoAddress);
		System.out.println("密送人邮箱:" + secretToAddress);

		emailTheme = emailThemeEText.getText().toString();
		if (!AbStrUtil.isEmpty(emailTheme) && !AbStrUtil.isEmpty(shoujianNames)) {
			// 向服务器发送数据
			if (emailType.equals("DPEMAIL")) {
				sendHeadEmailByNet(shoujianrenAddress, copytoAddress,
						secretToAddress, emailTheme, content, emailId, acType);
			} else if (emailType.equals("EMAIL")) {
				for (int i = 0; i < receviers.length; i++) {
					shoujianrenAddress = receviers[i] + ",";
				}
				shoujianrenAddress = shoujianrenAddress.substring(0,
						shoujianrenAddress.length() - 1);
				sendPuGuangEmailByNetWithAttach(shoujianrenAddress,
						copytoAddress, secretToAddress, emailTheme, content,
						emailId, acType, filenameArray, filesizeArray,
						byteArray);
				// Toast.makeText(this, "普光邮箱暂时不能发送邮件！",
				// Toast.LENGTH_SHORT).show();
			}

		} else {
			if (AbStrUtil.isEmpty(emailTheme)) {
				Toast.makeText(this, "邮件主题不能为空！", Toast.LENGTH_SHORT).show();
			} else if (AbStrUtil.isEmpty(shoujianNames)) {
				Toast.makeText(this, "收件人不能为空！", Toast.LENGTH_SHORT).show();
			}
		}

	}

	/** 调用文件选择软件来选择文件 **/
	private void showFileChooser() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("*/*");

		intent.addCategory(Intent.CATEGORY_OPENABLE);
		try {
			startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
					2);
		} catch (android.content.ActivityNotFoundException ex) {

			Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 文字编辑框 获得焦点 事件监听
	 */
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		int id = v.getId();
		/*
		 * // 收件人edittext if (id == R.id.email_receiver) {
		 * hideAddImage(addPeopleImageView); if (copyToEText.getTags().length <=
		 * 0 || copyToEText.getTags() == null) {
		 * invisibleLayout.setVisibility(View.GONE);
		 * textLinearLayout.setVisibility(View.VISIBLE); } } // 抄送edittext if
		 * (id == R.id.copyto) { hideAddImage(copyToImageView);
		 * invisibleLayout.setVisibility(View.VISIBLE);
		 * textLinearLayout.setVisibility(View.GONE); } // 密送edittext if (id ==
		 * R.id.secretsend) { hideAddImage(secretToImageView);
		 * invisibleLayout.setVisibility(View.VISIBLE);
		 * textLinearLayout.setVisibility(View.GONE); }
		 */

		// 邮件主题edittext
		if (id == R.id.write_emal_theme) {
			hideAddImage(null);
			if (copyToEText.getTags().length <= 0
					|| copyToEText.getTags() == null) {
				invisibleLayout.setVisibility(View.GONE);
				textLinearLayout.setVisibility(View.VISIBLE);
			}
		}

		// 邮件内容Edittext
		if (id == R.id.write_email_content) {
			hideAddImage(null);
			if (copyToEText.getTags().length <= 0
					|| copyToEText.getTags() == null) {
				invisibleLayout.setVisibility(View.GONE);
				textLinearLayout.setVisibility(View.VISIBLE);
			}
		}
	}

	/**
	 * 隐藏所有add图标，显示指定的add图标
	 */
	public void hideAddImage(ImageView addImageView) {
		for (ImageView im : imageViews) {
			im.setVisibility(View.INVISIBLE);
		}
		if (addImageView != null) {
			addImageView.setVisibility(View.VISIBLE);
		}
		if (hideaddattachmentLayout.getVisibility() == View.VISIBLE) {
			hideaddattachmentLayout.setVisibility(View.GONE);
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/** 选择联系人界面返回的数据 */
		ArrayList<SortModel> reSelectContactList = new ArrayList<SortModel>();
		if (resultCode == 0 && requestCode == 0) {

			// 初始化数据
			if (data.hasExtra("data")) {
				Log.i(TAG, "得到新增收件人成功");
				reSelectContactList = (ArrayList<SortModel>) data
						.getSerializableExtra("data");
				// System.out.println(reSelectContactList.toString());
				mSJRContacts.addAll(reSelectContactList);// 追加联系人

				initData(RECEIVETO);

			} else if (data.hasExtra("copydata")) {
				Log.i(TAG, "得到新增抄送人成功");
				reSelectContactList = (ArrayList<SortModel>) data
						.getSerializableExtra("copydata");
				// System.out.println(reSelectContactList.toString());
				mCOPYContacts.addAll(reSelectContactList);// 追加联系人

				initData(COPYTO);
			} else if (data.hasExtra("secretdata")) {
				Log.i(TAG, "得到新增密送人成功");
				reSelectContactList = (ArrayList<SortModel>) data
						.getSerializableExtra("secretdata");
				mSECRETContacts.addAll(reSelectContactList);// 追加联系人

				initData(SECTETTO);

			} else {
				Log.i(TAG, "选择了0个联系人");
				// 不进行任何操作
				// mSJRContacts = null;
			}

		}

		// 根据返回选择的文件，来进行上传操作
		else if (resultCode == Activity.RESULT_OK) {
			// 根据选择的文件得到uri
			Uri uri = data.getData();

			Log.i(TAG, "uri：" + uri);
			// 从uri中得到文件路径
			path = FileUtil.getFilePath(this, uri);

			Log.i(TAG, "文件url:" + path);
			String fileName = path.substring(path.lastIndexOf("/") + 1);
			System.out.println("文件名称" + fileName);
			AttachFile file = new AttachFile();
			file.setAttachName(fileName);
			file.setAttachPath(path);
			// 得到文件大小
			/*
			 * String filesize = String.valueOf(FileSizeUtil.getFileOrFilesSize(
			 * path, 2)) + "KB";
			 */
			String filesize;
			try {
				filesize = FileSizeUtil.getFileSize(new File(path)) + "";
				file.setAttachSize(filesize);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 设置文件缩略图
			Bitmap bmp = FileUtil.getImageFrompath(EmailWriteAct.this, path);
			Drawable drawable = new BitmapDrawable(bmp);
			file.setAttachImage(drawable);

			// 显示到gridview中
			showGrid(file);

		}

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		int code = intent.getIntExtra("code", -1);
		if (code != 100) {
			return;
		}
		System.out.println("--------------------------");
		ArrayList<String> paths = intent.getStringArrayListExtra("paths");

		for (String path : paths) {
			String fileName = path.substring(path.lastIndexOf("/") + 1);
			System.out.println("文件名称" + fileName);
			AttachFile file = new AttachFile();
			file.setAttachName(fileName);
			file.setAttachPath(path);
			// 得到文件大小
			//String filesize = FileSizeUtil.getAutoFileOrFilesSize(path);
			// file.setAttachSize(filesize);
			String filesize;
			try {
				filesize = FileSizeUtil.getFileSize(new File(path)) + "";
				file.setAttachSize(filesize);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 设置文件缩略图
			Bitmap bmp = FileUtil.getImageFrompath(EmailWriteAct.this, path);
			Drawable drawable = new BitmapDrawable(bmp);
			file.setAttachImage(drawable);
			// 显示到gridview中
			showGrid(file);

		}

	}

	/**
	 * 将选择的附件显示到gridview界面中
	 * 
	 * @param file
	 */
	private void showGrid(AttachFile file) {

		files.add(file);
		setGridView(files);

	}

	/**
	 * 设置GirdView参数，绑定数据
	 * 
	 * @param files2
	 *            文件list集合
	 */
	private void setGridView(ArrayList<AttachFile> files2) {
		int size = files2.size();
		int length = 100;
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		float density = dm.density;
		int gridviewWidth = (int) (size * (length + 4) * density);
		int itemWidth = (int) (length * density);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
		gridView.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
		gridView.setColumnWidth(itemWidth); // 设置列表项宽
		gridView.setHorizontalSpacing(10); // 设置列表项水平间距
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setNumColumns(size); // 设置列数量=列表集合数

		gridAdapter = new MyGridAdapter(files, EmailWriteAct.this);
		gridView.setAdapter(gridAdapter);
	}

	/**
	 * gridview点击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (parent == gridView) {
			Log.i(TAG, "点击了" + position);
			gridAdapter.getItemId(position);
			AttaachDialog dialog = new AttaachDialog(EmailWriteAct.this,
					R.style.dialog, position, files, gridAdapter);

			dialog.show();

		}

	}

	/**
	 * 初始化edittext的数据
	 * 
	 * @param j
	 *            1表示收件 2表示抄送 3表示密送
	 */
	private void initData(int j) {
		// 如果选择的联系人不为空

		if (j == RECEIVETO) {// 新增收件人赋值
			tagArray = getTagArray(mSJRContacts);
			System.out.println(recevierEText.getInputTagText());
			recevierEText.setTags(tagArray);

		}
		if (j == COPYTO) {// 新增抄送人赋值
			tagArray = getTagArray(mCOPYContacts);
			copyToEText.setTags(tagArray);

		}
		if (j == SECTETTO) {// 新增密送人赋值
			tagArray = getTagArray(mSECRETContacts);
			secretToEText.setTags(tagArray);
		}

	}

	/**
	 * 从list集合中得到的联系人名字集合
	 * 
	 * @param conList
	 * @return tagArray
	 */
	private List<String> getTagArray(ArrayList<SortModel> conList) {
		tagArray = new ArrayList<String>();
		for (int i = 0; i < conList.size(); i++) {
			System.out.println(conList.get(i).name);
			tagArray.add(conList.get(i).name);
		}
		return tagArray;

	}

	/**
	 * 显示隐藏的回复转发信息
	 * 
	 * @param i
	 */
	@SuppressWarnings("unchecked")
	private void setHideShow(int i) {
		shoujianrenInfoLayout.setVisibility(View.VISIBLE);
		webView.setVisibility(View.VISIBLE);
		emailData = new Email();
		files = (ArrayList<AttachFile>) getIntent().getSerializableExtra(
				"files");
		if (i == 1) {// 转发邮件 内容初始化
			emailData = (Email) getIntent().getSerializableExtra("copyto");
			emailId = emailData.getMessageID();

			// recevierEText.setTags(emailData.getFrom());
			// recevierEText.setText(emailData.getFrom());
			emailThemeEText.setText("转发：" + emailData.getSubject());
			// hideFajianrenEmail.setText("<" + emailData.getFromAddress() +
			// ">");
			hideFajianrenName.setText("" + emailData.getFrom() + "");
			hideFajianrenEmail.setText("<" + emailData.getFromAddress() + ">");
			// hideShoujianrenName.setText("" +AbStrUtil.getStr(
			// emailData.getTo()) + "");
			hideShoujianrenName.setText(emailData.getTo());
			hideTime.setText(emailData.getSentdata());
			hideTheme.setText(emailData.getSubject());
			webView.setVisibility(View.VISIBLE);
			webView.loadDataWithBaseURL(null, (String) emailData.getContent(),
					"text/html", "utf-8", null);

		}
		if (i == 2) {// 回复邮件 内容初始化
			emailData = (Email) getIntent().getSerializableExtra("reply");
			emailId = emailData.getMessageID();

			// recevierEText.setText(emailData.getFrom());
			recevierEText.setTags(emailData.getFrom());
			emailThemeEText.setText("回复：" + emailData.getSubject());
			hideFajianrenEmail.setText("<" + emailData.getFromAddress() + ">");
			hideFajianrenName.setText("" + emailData.getFrom() + "");
			// hideShoujianrenEmail.setText("<" +
			// AbStrUtil.getStr(emailData.getToAdress()) + ">");
			// hideShoujianrenName.setText("" +AbStrUtil.getStr(
			// emailData.getTo()) + "");
			hideShoujianrenName.setText(emailData.getTo());
			hideTime.setText(emailData.getSentdata());
			hideTheme.setText(emailData.getSubject());
			webView.setVisibility(View.VISIBLE);
			webView.loadDataWithBaseURL(null, (String) emailData.getContent(),
					"text/html", "utf-8", null);
		}
		// 判断如果intent中得到的附件信息不为空，那么就添加到gridview中
		if (files != null && !"EMAIL".equals(emailType)) {

			for (int j = 0; j < files.size(); j++) {
				// 重新为附件设置显示的图片
				Bitmap bitmap = FileUtil.getImageFrompath(EmailWriteAct.this,
						files.get(j).getAttachPath());
				Drawable drawable = new BitmapDrawable(bitmap);
				files.get(j).setAttachImage(drawable);
			//	files.get(j).setAttachSize("1024");
				setGridView(files);
			}

		}else {
			files= new ArrayList<AttachFile>();
		}

	}

	/**
	 * 点击收件人tag删除时的点击事件
	 */
	private TagGroup.OnTagClickListener mSJRTagCkListener = new TagGroup.OnTagClickListener() {
		@Override
		public void onTagClick(String tag) {

			deleteTag(tag, RECEIVETO);
		}
	};
	/**
	 * 点击抄送人tag删除时的点击事件
	 */
	private TagGroup.OnTagClickListener mCopyTagCkListener = new TagGroup.OnTagClickListener() {
		@Override
		public void onTagClick(String tag) {

			deleteTag(tag, COPYTO);
		}
	};
	/**
	 * 点击密送人tag删除时的点击事件
	 */
	private TagGroup.OnTagClickListener mSecretClickListener = new TagGroup.OnTagClickListener() {
		@Override
		public void onTagClick(String tag) {
			Log.i(TAG, "点击的联系人名字：" + tag);
			deleteTag(tag, SECTETTO);
		}
	};

	/**
	 * 删除标签
	 * 
	 * @param tag
	 * @param a
	 *            标记点击的是哪里面的tag 1代表收件人 2抄送人 3密送人
	 */
	private void deleteTag(String tag, int a) {
		if (a == RECEIVETO) {

			for (int j = 0; j < mSJRContacts.size(); j++) {
				// 如果收件人中 有姓名 跟tag标签相等 删除收件人列表中的这一项
				if (mSJRContacts.get(j).name.equals(tag)) {
					mSJRContacts.remove(j);
				}
			}
		} else if (a == COPYTO) {
			for (int j = 0; j < mCOPYContacts.size(); j++) {
				// 如果收件人中 有姓名 跟tag标签相等 删除收件人列表中的这一项
				if (mCOPYContacts.get(j).name.equals(tag)) {
					mCOPYContacts.remove(j);
				}
			}
		} else {
			for (int j = 0; j < mSECRETContacts.size(); j++) {
				// 如果收件人中 有姓名 跟tag标签相等 删除收件人列表中的这一项
				if (mSECRETContacts.get(j).name.equals(tag)) {
					mSECRETContacts.remove(j);
				}
			}
		}

	}

	/**
	 * 得到已输入的新的联系人集合
	 * 当手动输入联系人以后，如果点击新增联系人按钮，之前输入的会被清除，此方法是为了判断联系人列表中是否包含手动输入的，如果不包含
	 * 就添加到list列表中
	 */
	public void getInputContact(int flag) {
		TagGroup tagGroup = null;
		ArrayList<SortModel> arrayList = new ArrayList<SortModel>();
		if (flag == RECEIVETO) {
			tagGroup = recevierEText;
			arrayList = mSJRContacts;
		}
		if (flag == COPYTO) {
			tagGroup = copyToEText;
			arrayList = mCOPYContacts;
		}
		if (flag == SECTETTO) {
			tagGroup = secretToEText;
			arrayList = mSECRETContacts;
		}

		if (tagGroup.getTags().length > 0) {

			for (String tag : tagGroup.getTags()) {
				Boolean[] isHave = new Boolean[15];
				for (int j = 0; j < arrayList.size(); j++) {
					if (tag.equals(arrayList.get(j).name)
							|| tag.equals(arrayList.get(j).number)) {
						isHave[j] = true;
					} else {
						isHave[j] = false;
					}
				}
				System.out.println(Arrays.toString(isHave));
				if (!Arrays.toString(isHave).contains("true")) {
					SortModel model = new SortModel();
					model.name = tag;
					model.number = tag;
					arrayList.add(model);

				}
			}

		} else {
			Log.i(TAG, "不存在标签！");
		}
	}

	/**
	 * 普光邮箱发送邮件
	 * 
	 * @param address
	 *            收件人邮箱
	 * @param copyToAddress
	 *            抄送人邮箱
	 * @param secretToAddress
	 *            密送人邮箱
	 * @param Subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @param emailId
	 *            邮件ID
	 * @param acType
	 *            邮件类型 新邮件 转发 回复
	 * 
	 */
	private void sendPuGuangEmailByNetWithAttach(final String address,
			final String copyToAddress, final String secretToAddress,
			final String Subject, final String content, final String emailId,
			final String acType, final String[] filenameArray,
			final int[] filesizeArray, final Object[] byteArray) {
		Log.i(TAG, "加载收件箱数据");
		new AsyncTask<Void, Void, JResponseObject>() {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 加载dialog显示
				LoadingDataUtilBlack.show(EmailWriteAct.this);
			}

			@Override
			protected JResponseObject doInBackground(Void... params) {
				// 创建PO
				JParamObject PO = JParamObject.Create();
				JResponseObject RO = null;
				String DPtokenId = (String) EnvironmentVariable.getProperty(
						"EmailTokenId", "");

				PO.SetValueByParamName("WB_SYS_KEY", "EMAIL");
				PO.SetValueByParamName("EMAIL_systemmethod", "SendMail");
				PO.SetValueByParamName("EMAIL_params_Actype", acType);
				PO.SetValueByParamName("EMAIL_params_Subject", Subject);
				PO.SetValueByParamName("EMAIL_params_Body", content);
				PO.SetValueByParamName("EMAIL_params_To", address);
				PO.SetValueByParamName("EMAIL_params_Bcc", secretToAddress);
				PO.SetValueByParamName("EMAIL_params_tokenIDFromMoblie",
						DPtokenId);
				PO.SetValueByParamName("EMAIL_params_Cc", copyToAddress);

				if (emailId != null && !emailId.equals("")) {
					PO.SetValueByParamName("EMAIL_params_EmailID", emailId);
				} else {
					PO.SetValueByParamName("EMAIL_params_EmailID", "");
				}

				PO.setValue("EMAIL_params_filename", filenameArray);
				PO.setValue("EMAIL_params_filebyte", byteArray);
				PO.setValue("EMAIL_params_filesize", filesizeArray);

				try {
					// 连接服务器
					RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
					System.out.println("..........");
				} catch (Exception e) {
					e.printStackTrace();
				}
				return RO;
			}

			@Override
			protected void onPostExecute(JResponseObject result) {
				super.onPostExecute(result);
				if (result != null) {
					Map map = result.getResponseMap();
					if (map.containsKey("EMAIL")) {

						EFDataSet emailEFDataSet = (EFDataSet) map.get("EMAIL");
						if (emailEFDataSet != null) {

							EFRowSet rowSet = (EFRowSet) emailEFDataSet
									.getRowSetArray().get(0);
							if ((rowSet.getString("Result", "")).equals("1")) {
								Toast.makeText(EmailWriteAct.this, "邮件发送成功！",
										Toast.LENGTH_SHORT).show();
							} else if ((rowSet.getString("Result", ""))
									.equals("0")) {
								Toast.makeText(EmailWriteAct.this, "邮件发送失败！",
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(EmailWriteAct.this, "邮件发送失败！",
									Toast.LENGTH_SHORT).show();
						}
					}
					LoadingDataUtilBlack.dismiss();

				} else {
					Toast.makeText(EmailWriteAct.this, "邮件发送失败！",
							Toast.LENGTH_SHORT).show();
					LoadingDataUtilBlack.dismiss();
				}
			}
		}.execute();

	}

	/**
	 * 总部邮箱发送邮件
	 * 
	 * @param address
	 *            收件人邮箱
	 * @param copyToAddress
	 *            抄送人邮箱
	 * @param secretToAddress
	 *            密送人邮箱
	 * @param Subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @param emailId
	 *            邮件ID
	 * @param acType
	 *            邮件类型 新邮件 转发 回复
	 * 
	 */
	private void sendHeadEmailByNet(final String address,
			final String copyToAddress, final String secretToAddress,
			final String Subject, final String content, final String emailId,
			final String acType) {
		Log.i(TAG, "加载收件箱数据");
		new AsyncTask<Void, Void, JResponseObject>() {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 加载dialog显示
				LoadingDataUtilBlack.show(EmailWriteAct.this);
			}

			@Override
			protected JResponseObject doInBackground(Void... params) {
				// 创建PO
				JParamObject PO = JParamObject.Create();
				JResponseObject RO = null;
				String DPtokenId = (String) EnvironmentVariable.getProperty(
						"DPEmailTokenId", "");

				PO.SetValueByParamName("WB_SYS_KEY", "DPEMAIL");
				PO.SetValueByParamName("DPEMAIL_systemmethod", "SendMail");
				PO.SetValueByParamName("DPEMAIL_params_Actype", acType);
				PO.SetValueByParamName("DPEMAIL_params_Subject", Subject);
				PO.SetValueByParamName("DPEMAIL_params_Body", content);
				PO.SetValueByParamName("DPEMAIL_params_To", address);
				PO.SetValueByParamName("DPEMAIL_params_Bcc", secretToAddress);
				PO.SetValueByParamName("DPEMAIL_params_tokenIDFromMoblie",
						DPtokenId);
				PO.SetValueByParamName("DPEMAIL_params_Cc", copyToAddress);

				if (emailId != null && !emailId.equals("")) {
					PO.SetValueByParamName("DPEMAIL_params_EmailID", emailId);
				} else {
					PO.SetValueByParamName("DPEMAIL_params_EmailID", "");
				}

				try {
					// 连接服务器
					RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
					System.out.println("..........");
				} catch (Exception e) {
					e.printStackTrace();
				}
				return RO;
			}

			@Override
			protected void onPostExecute(JResponseObject result) {
				super.onPostExecute(result);
				if (result != null) {
					Map map = result.getResponseMap();
					if (map.containsKey("DPEMAIL")) {
						EFDataSet emailEFDataSet = (EFDataSet) map
								.get("DPEMAIL");
						if (emailEFDataSet != null) {
							EFRowSet rowSet = (EFRowSet) emailEFDataSet
									.getRowSetArray().get(0);
							if ((rowSet.getString("result", "")).equals("1")) {
								Toast.makeText(EmailWriteAct.this, "邮件发送成功！",
										Toast.LENGTH_SHORT).show();
							} else if ((rowSet.getString("result", ""))
									.equals("0")) {
								Toast.makeText(EmailWriteAct.this, "邮件发送失败！",
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(EmailWriteAct.this, "邮件发送失败！",
									Toast.LENGTH_SHORT).show();
						}
					}
					LoadingDataUtilBlack.dismiss();

				} else {
					Toast.makeText(EmailWriteAct.this, "邮件发送失败！",
							Toast.LENGTH_SHORT).show();
					LoadingDataUtilBlack.dismiss();
				}
			}
		}.execute();

	}
}
